package com.timofeyco.springsocialwithscribedemo.social.twitter.impl;

import com.timofeyco.springsocialwithscribedemo.social.OAuth1Manager;
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.TwitterApi;
import org.scribe.model.Token;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;

/**
 * Product: Spring Social with Scribe demo
 * Author: Timofey Tatarinov
 * Date: 9/21/11
 * Time: 8:59 PM
 */
public class TwitterOAuthManager implements OAuth1Manager {
    private static final String AUTHORIZE_URL = "https://api.twitter.com/oauth/authenticate?oauth_token=";

    private OAuthService service;
    private Token requestToken;

    private String consumerSecret;
    private String consumerKey;
    private String redirectURI;

    private void initService() {
        service = new ServiceBuilder()
                 .provider(TwitterApi.class)
                 .apiKey(consumerKey)
                 .apiSecret(consumerSecret)
                 .callback(redirectURI)
                 .build();
    }

    public String getAuthorizationURL() {
        if (service == null) {
            initService();
        }
        requestToken = service.getRequestToken();
        return AUTHORIZE_URL + requestToken.getToken();
    }

    public Token getOAuthAccessToken(String verifierCode) {
        if (service == null) {
            initService();
        }
        Verifier verifier = new Verifier(verifierCode);
        Token token = service.getAccessToken(requestToken, verifier);
        return token;
    }

    public OAuthService getService() {
        return service;
    }

    public String getConsumerSecret() {
        return consumerSecret;
    }

    public String getConsumerKey() {
        return consumerKey;
    }

    public void setConsumerSecret(String consumerSecret) {
        this.consumerSecret = consumerSecret;
    }

    public void setConsumerKey(String consumerKey) {
        this.consumerKey = consumerKey;
    }

    public void setRedirectURI(String redirectURI) {
        this.redirectURI = redirectURI;
    }
}
